package gspushmq.util;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArraySet;

import org.java_websocket.WebSocket;

import gspushmq.model.ApiMessage;
import gspushmq.model.ApiMessageType;
import gspushmq.model.DataBase;
import gspushmq.model.Message;
import gspushmq.model.MessageType;
import gspushmq.model.User;
import gspushmq.v1.produce.GGDataStorage;
import gspushmq.v1.subscribe.GGSubscribe;

/**
 * @author yutao
 * @version 1.0
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2018年12月19日上午11:27:19
 * @since JDK1.7
 */
public class ClearMemoryUtil {

    /**
     * 清理内存
     *
     * @param wst
     * @author yutao
     * @date 2018年12月19日上午11:29:36
     */
    public static void clearMemory(WebSocket wst) {

        if (wst == null) {
            return;
        }
        User user = GGSubscribe.wstUser.get(wst);
        if (user == null) {
            return;
        }
        
        boolean uBool = false;
        //查找还有没有终端进行链接  没有就删除
        Iterator<Entry<WebSocket, User>> wstIt = GGSubscribe.wstUser.entrySet().iterator();
        while (wstIt.hasNext()) {
            Entry<WebSocket, User> o = wstIt.next();
            User uu = o.getValue();

            if (uu.equals(user)) {
                uBool = true;
            }
        }
        if (!uBool) {
            GGSubscribe.userWst.remove(user);
        }

        String aidLong = user.getAccountId();
        if (aidLong == null) {
            GGLogger.warn(ClearMemoryUtil.class, "-----cleanMemory------ 账号id没拿到---");
            return;
        }

        String accountId = aidLong.toString();

        Message message = GGSubscribe.wstMessage.get(wst);
        if (message != null) {
            String requestId = message.getRequest_id();
//			String mqSubType = message.getMq_sub_type();
            String productLine = message.getProduct_line();

            Iterator<Entry<ApiMessageType, DataBase>> iterator = GGDataStorage.ApiBaseMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<ApiMessageType, DataBase> o = iterator.next();

                ApiMessageType apiType = o.getKey();

                String messageFlag = apiType.getMessageFlag();
                String baseKey = accountId + "|" + messageFlag;
                DataBase value = o.getValue();
                if (value == null) {
                    continue;
                }
                Map<String, Object> accountIdsMap = value.getAccountIdsMap();
                if (accountIdsMap == null) {
                    continue;
                }
                if (uBool) {
                	//这一类数据只要有一个产品线还在用，就不能清除内存数据
					continue;
				}
                Object baseObj = accountIdsMap.get(baseKey);
                baseObj = baseObj == null?null:null;
                accountIdsMap.remove(baseKey);
                GGLogger.warn(ClearMemoryUtil.class, "-----cleanMemory-----清除内存数据- ApiBaseMap---" + baseKey + "---集合--accountIdsMap");
            }


            Iterator<Entry<ApiMessageType, ConcurrentSkipListSet<ApiMessage>>> apiUrlMess = GGSubscribe.ApiUrlMessage.entrySet().iterator();
            while (apiUrlMess.hasNext()) {
                Entry<ApiMessageType, ConcurrentSkipListSet<ApiMessage>> o = apiUrlMess.next();

                Set<ApiMessage> value = o.getValue();
                if (value == null) {
                    continue;
                }
                Iterator<ApiMessage> setIt = value.iterator();
                while (setIt.hasNext()) {
                    ApiMessage apiMess = setIt.next();
                    String aId = apiMess.getAccount_id();
                    if (accountId.equals(aId) && requestId.equals(apiMess.getRequest_id()) && productLine.equals(apiMess.getProduct_line())) {
                        setIt.remove();
                        if (value.isEmpty()) {
                            apiUrlMess.remove();
                        }
                        GGLogger.warn(ClearMemoryUtil.class, "-----cleanMemory-----清除内存数据--ApiUrlMessage--" + apiMess);
                        break;
                    }
                }
            }

            Iterator<Entry<MessageType, ConcurrentSkipListSet<Message>>> messIt = GGSubscribe.messWocketMap.entrySet().iterator();
            while (messIt.hasNext()) {
                Entry<MessageType, ConcurrentSkipListSet<Message>> o = messIt.next();
                Set<Message> messSet = o.getValue();
                if (messSet == null) {
                    continue;
                }
                Iterator<Message> msIt = messSet.iterator();
                while (msIt.hasNext()) {
                    Message mess = msIt.next();
                    String aId = mess.getAccount_id();
//					if(accountId.equals(aId) && requestId.equals(mess.getRequest_id()) && mqSubType.equals(mess.getMq_sub_type())
//							&& productLine.equals(mess.getProduct_line())) {
                    if (accountId.equals(aId)
                            && productLine.equals(mess.getProduct_line())) {
                        msIt.remove();
                        if (messSet.isEmpty()) {
                            messIt.remove();
                        }
                        GGLogger.warn(ClearMemoryUtil.class, "-----cleanMemory-----清除内存数据--messWocketMap--" + mess);
                        break;
                    }
                }
            }
        }
        GGSubscribe.wstUser.remove(wst);
        GGSubscribe.wstMessage.remove(wst);
    }
}
